package com.zwj.config.async;

import org.springframework.aop.interceptor.AsyncUncaughtExceptionHandler;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.AsyncConfigurer;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;

import java.lang.reflect.Method;
import java.util.concurrent.Executor;
import java.util.concurrent.ThreadPoolExecutor;

/**
 * @author snake
 * @version 1.0
 * @createTime 2025/8/3
 */
@Configuration
@EnableAsync
public class AsyncConfig implements AsyncConfigurer {
    /**
     * 获取异步任务执行器
     * 该方法用于创建和配置线程池任务执行器，用于处理异步任务。
     * 配置包括核心线程数、最大线程数、队列容量、线程名称前缀和拒绝执行策略等参数。
     *
     * @return Executor 返回配置好的线程池任务执行器实例
     */
    @Override
    @Bean(name = "taskExecutor")
    public Executor getAsyncExecutor() {
        // 创建线程池任务执行器实例
        ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();

        // 配置线程池参数
        executor.setCorePoolSize(5);
        executor.setMaxPoolSize(10);
        executor.setQueueCapacity(100);
        executor.setThreadNamePrefix("Async-");
        executor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());

        // 初始化执行器
        executor.initialize();
        return executor;
    }

    /**
     * 获取异步未捕获异常处理器
     *
     * @return AsyncUncaughtExceptionHandler 异步未捕获异常处理器实例
     */
    @Override
    public AsyncUncaughtExceptionHandler getAsyncUncaughtExceptionHandler() {
        // 创建并返回自定义的异步异常处理器
        return new CustomAsyncExceptionHandler();
    }


    static class CustomAsyncExceptionHandler implements AsyncUncaughtExceptionHandler {
        /**
         * 处理异步方法中未捕获的异常
         *
         * @param ex 异常对象
         * @param method 抛出异常的方法
         * @param params 方法调用时的参数列表
         */
        @Override
        public void handleUncaughtException(Throwable ex, Method method, Object... params) {
            // 打印异常信息到标准错误输出
            System.err.println("异步方法异常: " + method.getName());
            System.err.println("异常信息: " + ex.getMessage());
            ex.printStackTrace();
        }

    }

}
